const CompanyHistory = require("../model/companyHistory");
const { validationResult, checkSchema } = require("express-validator");
const { updateCompanyInfo } = require("./companyInfo");

module.exports = {
  // 获取发展历程列表
  getCompanyHistoryList: async (req, res) => {
    const { page, limit } = req.query;
    const offset = (page - 1) * limit;
    try {
      const companyHistoryList = await CompanyHistory.findAndCountAll({
        offset,
        limit,
        order: [["date", "DESC"]],
      });
      res.json({
        code: 200,
        message: "获取成功",
        data: companyHistoryList,
      });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  editCompanyHistory: async (req, res) => {
    const { h_id, date, content } = req.body;
    try {
      // 判断 h_id 是否存在, 存在则修改，不存在则是添加
      if (h_id) {
        // 更新是否成功
        const existingRecord = await CompanyHistory.findOne({ where: { h_id } });
        if (!existingRecord) {
          return res.json({ code: -1, message: "记录不存在" });
        }
        // 如果日期发生变化，检查日期是否已存在
        if (date && date !== existingRecord.date) {
          const isExist = await await CompanyHistory.findOne({ where: { date, h_id } }); // 排除当前记录
          if (isExist) {
            return res.json({ code: -1, message: "日期已存在" });
          }
        }
        const updateData = {};
        if (date && date !== existingRecord.date) updateData.date = date;
        if (content && content !== existingRecord.content) updateData.content = content;
        if (Object.keys(updateData).length > 0) {
          const updateResult = await CompanyHistory.update(updateData, { where: { h_id } });
          if (updateResult[0] <= 0) {
            return res.json({ code: -1, message: "更新失败" });
          }
        }
        return res.json({ code: 1, message: "更新成功" });
      } else {
        // 查询 date是否存在
        const isExist = await CompanyHistory.findOne({ where: { date } });
        if (isExist) {
          return res.json({ code: -1, message: "日期已存在" });
        }
        const addResult = await CompanyHistory.create({ date, content });
        if (!addResult) {
          return res.json({ code: -1, message: "添加失败" });
        }
        return res.json({ code: 1, message: `添加成功` });
      }
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  deleteCompanyHistory: async (req, res) => {
    const { h_id } = req.query;
    try {
      const deleteResult = await CompanyHistory.destroy({ where: { h_id } });
      if (deleteResult <= 0) {
        return res.json({ code: -1, message: "删除失败" });
      }
      return res.json({ code: 1, message: "删除成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
};
